package com.weiweiqin.controller.home;

import com.weiweiqin.model.*;
import com.weiweiqin.service.*;
import com.weiweiqin.utils.BigDemicalUtil;
import com.weiweiqin.utils.kanjia.PingDuoDuoReduceRule;
import com.weiweiqin.vo.common.GoodsQueryVO;
import com.weiweiqin.vo.common.Page;
import com.weiweiqin.vo.common.Result;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("front/game")
public class FGameController {

	private static final Logger logger = LoggerFactory.getLogger(FGameController.class);

	@Autowired
	private GameService gameService;

	@Autowired
	private GamelogService gamelogService;

	@Autowired
	private KhSettingService khSettingService;

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private PrizeService prizeService;

	@RequestMapping(value = "/gameStart.do", method = { RequestMethod.POST})
	@ResponseBody
	public String gameStart(int goodsId,HttpSession session) {
		Result result = new Result();
		try {
			Customer customer = (Customer) session.getAttribute("customer");
			//数据库实时获取用户
			customer = customerService.get(customer.getId());
			int returnResult = gameService.gameStart(goodsId, customer);
			if(returnResult == -1) {
				result.setResult(false);
				result.setErrorMsg("您的余额不足，请先充值！");
				return result.toJson();
			}
			Map<String,Object> mp = new HashMap<String,Object>();
			String key = returnResult+"_"+goodsId;
			session.setAttribute("gamekey",key);
			Map<String, Map<String, Object>> gParams = getGParams(goodsId,customer);
			Map<String,Object> resu = new HashMap<String,Object>();
			resu.put("gameId",returnResult);
			resu.put("gParams",gParams);
			result.setResult(true);
			result.setObj(resu);
			return result.toJson();
		} catch (Exception e) {
			logger.error("内部服务器错误",e);
			result.setErrorMsg("内部服务器错误");
			result.setResult(false);
			return result.toJson();
		}
	}

	private Map<String,Map<String,Object>> getGParams(int goodsId,Customer customer){
		Map<String,Map<String,Object>> params = new HashMap<String,Map<String,Object>>();
		Page page = new Page();
		Map<String,Object> conditions = new HashMap<String, Object>();
		Goods goods = goodsService.get(goodsId);
		List<KhSetting> khSettings = khSettingService.pageList(page, conditions);
		KhSetting khSetting = null;
		if(null != khSettings && khSettings.size()>0) {
			khSetting = khSettings.get(0);
		}else {
			logger.error("未配置参数信息.................................");
			return params;
		}

		//最后一次成功id
		int lastWinId = gamelogService.getLastWinId(goodsId);
		//连续失败次数
		int failNum = gamelogService.getFailNum(lastWinId, goodsId);

		//数量
		int oneInit = khSetting.getOneInit();
		//时间
		int oneInitS = khSetting.getOneInitS();
		//通关数量
		int oneInitC = khSetting.getOneInitC();

		int twoInit = khSetting.getTwoInit();
		int twoInitS = khSetting.getTwoInitS();
		int twoInitC = khSetting.getTwoInitC();

		int threeInit = khSetting.getThreeInit();
		int threeInitS = khSetting.getThreeInitS();
		int threeInitC = khSetting.getThreeInitC();

		//速度值
		double speed_level1 = 0.002;
		double speed_level2 = 0.003;
		double speed_level3 = 0.001;
		double speed_level9 = 0.009;
		if (failNum >= goods.getHard()) {
			int hard_num = goods.getHardNum();//数量系数
			int hard_time = goods.getHardTime();  //时间系数
			double hard_speed = goods.getHardSpeed();  //速度
			oneInitS = oneInitS - hard_time;        //  1 时间
			oneInitC = oneInitC - hard_num;        //  1 通关数量
			twoInitS = twoInitS - hard_time;        //  2 时间
			twoInitC = twoInitC - hard_num;        //  2 通关数量
			threeInitS = threeInitS - hard_time;    //  3 时间
			threeInitC = threeInitC - hard_num;    //  3 通关数量
			//转速
			if (hard_speed > 0) {
				speed_level1 = hard_speed;
				speed_level2 = hard_speed;
				speed_level3 = hard_speed;
				speed_level9 = hard_speed;
			}
		}

		Map<String,Object> level1Params = new HashMap<String,Object>();
		Map<String,Object> level2Params = new HashMap<String,Object>();
		Map<String,Object> level3Params = new HashMap<String,Object>();
		params.put("Level1_PARAMETERS",level1Params);
		params.put("Level2_PARAMETERS",level2Params);
		params.put("Level3_PARAMETERS",level3Params);
		double[] ROTAION_SPEED_ARRAY = {-0.04,-0.02,-0.01,0.01,0.02,0.04};
		level1Params.put("ROTAION_SPEED_ARRAY",ROTAION_SPEED_ARRAY);
		level1Params.put("rotationAccelerationSpeed",speed_level1);
		double[] levelArray = {oneInit,oneInitC,0.02,oneInitS};
		level1Params.put("levelArray",levelArray);

		double[] ROTAION_SPEED_ARRAY2 = {-0.06,-0.05,-0.02,0.02,0.05,0.06};
		level2Params.put("ROTAION_SPEED_ARRAY",ROTAION_SPEED_ARRAY2);
		level2Params.put("rotationAccelerationSpeed",speed_level2);
		double[] levelArray2 = {twoInit,twoInitC,0.02,twoInitS};
		level2Params.put("levelArray",levelArray2);

		//为该用户单独设置了困难模式，想哭
		if(customer.getHard() ==1) {
			double[] ROTAION_SPEED_ARRAY3 = {-0.12,-0.09,-0.07,0.12,0.08,0.07,0.01};
			level3Params.put("ROTAION_SPEED_ARRAY",ROTAION_SPEED_ARRAY3);
			level3Params.put("rotationAccelerationSpeed",speed_level9);
			double[] levelArray3 = {threeInit,threeInitC,0.12,threeInitS};
			level3Params.put("levelArray",levelArray3);
		//为该用户单独设置了非常困难模式，直接哭了
		} else if(customer.getHard() == 2) {
			double[] ROTAION_SPEED_ARRAY3 = {-0.15,-0.13,-0.11,0.15,0.15,0.11,0.07};
			level3Params.put("ROTAION_SPEED_ARRAY",ROTAION_SPEED_ARRAY3);
			level3Params.put("rotationAccelerationSpeed",speed_level9);
			double[] levelArray3 = {threeInit,threeInitC,0.15,threeInitS};
			level3Params.put("levelArray",levelArray3);
		//为该用户单独设置了变态难模式，当场晕死
		}else if(customer.getHard() == 3){
			double[] ROTAION_SPEED_ARRAY3 = {-0.18,-0.16,-0.14,0.18,0.18,0.14,0.10};
			level3Params.put("ROTAION_SPEED_ARRAY",ROTAION_SPEED_ARRAY3);
			level3Params.put("rotationAccelerationSpeed",speed_level9);
			double[] levelArray3 = {threeInit,threeInitC,0.18,threeInitS};
			level3Params.put("levelArray",levelArray3);
		}else {
			//通过概率控制难度
			int level = getgamelevel(khSetting.getChance(),goodsId);
			if(level == 9) {
				double[] ROTAION_SPEED_ARRAY3 = {-0.09,-0.07,-0.05,0.09,0.06,0.05,0.01};
				level3Params.put("ROTAION_SPEED_ARRAY",ROTAION_SPEED_ARRAY3);
				level3Params.put("rotationAccelerationSpeed",speed_level9);
				double[] levelArray3 = {threeInit,threeInitC,0.09,threeInitS};
				level3Params.put("levelArray",levelArray3);
			} else {
				double[] ROTAION_SPEED_ARRAY3 = {-0.05,-0.03,-0.02,0.01,0.02,0.03,0.05};
				level3Params.put("ROTAION_SPEED_ARRAY",ROTAION_SPEED_ARRAY3);
				level3Params.put("rotationAccelerationSpeed",speed_level3);
				double[] levelArray3 = {threeInit,threeInitC,0.01,threeInitS};
				level3Params.put("levelArray",levelArray3);
			}
		}

		Map<String,Object> failPara = new HashMap<String,Object>();
		failPara.put("cheatDistance","AimBullet.w*5");
		failPara.put("startJudgeCheatDistanceNum",3);
		params.put("fail_PARAMETERS",failPara);
		return params;
	}

	private int getgamelevel(int chance,int goodsId) {
		//当前已中奖数量
		//当前游戏数量
		//中奖概率
		//if(当前中奖数量除以 当前游戏数量 <=中奖概率){
		// 第三关难度为高
		//
		//}else{
		//第三关游戏难度为低
		//
		//}
		//输出游戏难度
		Map<String,Object> conditions = new HashMap<String, Object>();
		//所有商品总中奖数
		int totalPrizeCount = prizeService.totalCount(conditions);
		//该商品总共游戏数量
		int allNumByGoodsId = gamelogService.getAllNumByGoodsId(goodsId);
		if((totalPrizeCount/allNumByGoodsId) > (chance/100)){
			//高难度
			return 9;
		}else{
			//TODO 暂时为难度模式
			//低难度
			return 9;
		}
	}

	@RequestMapping(value = "/gameSuccess.do", method = { RequestMethod.POST})
	@ResponseBody
	public String gameSuccess(int goodsId,int gameId,int level,HttpSession session) {
		Result result = new Result();
		String key = gameId+"_"+goodsId;
		Object isSafe = session.getAttribute("gamekey");
		if(null == isSafe || !key.equals(isSafe.toString())) {
			result.setErrorMsg("你的金币已经不足，无法完成闯关！");
			result.setResult(false);
			return result.toJson();
		}
		try {
			Customer customer = (Customer) session.getAttribute("customer");
			gameService.gameSuccess(goodsId, customer.getId(), level,gameId);
			session.removeAttribute("gamekey");
		} catch (Exception e) {
			logger.error("内部服务器错误",e);
			result.setErrorMsg("内部服务器错误");
			session.removeAttribute("gamekey");
			result.setResult(false);
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/gameFail.do", method = { RequestMethod.POST})
	@ResponseBody
	public String gameFail(int goodsId,int gameId,int level,HttpSession session) {
		Result result = new Result();
		String key = gameId+"_"+goodsId;
		Object isSafe = session.getAttribute("gamekey");
		if(null == isSafe || !key.equals(isSafe.toString())) {
			result.setErrorMsg("你的金币已经不足，无法完成闯关！");
			result.setResult(false);
			return result.toJson();
		}
		try {
			Customer customer = (Customer) session.getAttribute("customer");
			gameService.gameFail(customer.getId(), level,gameId);
			session.removeAttribute("gamekey");
		} catch (Exception e) {
			session.removeAttribute("gamekey");
			logger.error("内部服务器错误",e);
			result.setErrorMsg("内部服务器错误");
			result.setResult(false);
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}

}
